﻿using AutoLoadDLL.Common;
using AutoLoadDLL.Model;
using Microsoft.Win32;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Forms;

namespace AutoLoadDLL.ViewModel
{
    public class MainViewModel
    {
        public MainModel mainModel { get; set; } = new MainModel();
        public ProgramModel programModel { get; set; } = new ProgramModel();
        public RelayCommand AutoLoadCommand { get; set; }
        public RelayCommand BrowseCommand { get; set; }
        public RelayCommand AddRegistryCommand { get; set; }
        public RelayCommand DeleteRegistryCommand { get; set; }
        public RelayCommand ExitClickCommand { get; set; }
        // .NE程序的名字和程序路径
        public ObservableCollection<ProgramModel> Programs { get; set; } = new ObservableCollection<ProgramModel>();
        public MainViewModel()
        {
            AutoLoadCommand = new RelayCommand(new Action<object>(AutoLoad), new Func<object, bool>((o) =>
            {
                return true;
            }));
            BrowseCommand = new RelayCommand(new Action<object>(BrowseNET), new Func<object, bool>((o) => { return true; }));
            AddRegistryCommand = new RelayCommand(new Action<object>(AddRegistry), new Func<object, bool>((o) => { return true; }));
            DeleteRegistryCommand = new RelayCommand(new Action<object>(DeleteRegistry), new Func<object, bool>((o) => { return true; }));
            ExitClickCommand = new RelayCommand(new Action<object>(ExitClick), new Func<object, bool>((o) => { return true; }));
        }
        /// <summary>
        /// 退出窗口
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ExitClick(object obj)
        {
            if (obj is Window)
            {
                (obj as Window).Close();
            }
        }

        /// <summary>
        /// 删除注册表
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void DeleteRegistry(object obj)
        {
            if (obj is ProgramModel)
            {
                //获取列表框中当前选择的项
                var textContent = obj as ProgramModel;

                if (textContent != null)
                {
                    //显示警告对话框提示
                    DialogResult result = System.Windows.Forms.MessageBox.Show($"确定删除{textContent.Name}注册表项吗？", 
                        "警告",MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        //删除
                         
                        if (CreateDemandLoading.RemoveDemandLoadingEntries(textContent.Name, true))  //删除成功
                        {
                            //从列表框中移除对应的注册表项
                            Programs.Remove(textContent);
                        }
                    }
                }
            }


        }

        /// <summary>
        /// 加入注册表
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void AddRegistry(object obj)
        {
            //应用程序名
            string appName = mainModel.TextApp;
            //应用描述
            string appDesc = mainModel.TextAppDesc;
            //应用程序路径
            string appPath = mainModel.DllFileName;
            //添加注册表项到Applications键下
            CreateDemandLoading.CreateDemandLoadingEntries(appName, appDesc, appPath, true, false, 2);
            //应用程序的有关信息添加到列表中
            programModel.Name = appName;
            programModel.Path = appPath;
            this.Programs.Add(programModel);
        }

        /// <summary>
        /// 选择要加载的.NET程序
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void BrowseNET(object obj)
        {
            System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
            openFileDialog.Filter = "DLL Files (*.dll)|*.dll";
            openFileDialog.Multiselect = false;
            DialogResult result = openFileDialog.ShowDialog();
            //判断用户是否通过打开文件夹对话框选择了.NET 程序集

            if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(openFileDialog.FileName))
            {
                // 获取选择的 .NET程序 DLL 文件名
                //string dllFileName = Path.GetFileName(openFileDialog.FileName);
                string dllFileName = openFileDialog.FileName;
                mainModel.DllFileName = dllFileName;
                //选择的.NET 程序集的文件名 （不含路径与后缀）, 作为应用程序名
                mainModel.TextApp = Path.GetFileNameWithoutExtension(dllFileName);
                mainModel.TextAppDesc = mainModel.TextApp;
            }
        }
        /// <summary>
        /// 显示当前的Cad版本信息和已加载的.NET程序
        /// </summary>
        /// <param name="obj"></param>
        private void AutoLoad(object obj)
        {
            //获取当前AutoCad的注册表键名
            string cadKeyName = CreateDemandLoading.GetAutoCadKeyName();

            try
            {
                //打开HKEY_LOCAL_MACHINE下当前AutoCad的注册表键以获得版本号
                RegistryKey keyCad = Registry.LocalMachine.OpenSubKey(cadKeyName);
                //找到当前AutoCad版本号
                string cadName = keyCad?.GetValue("ProductName")?.ToString();
                mainModel.TextCurCAD = cadName;
                if (cadName == null)
                {
                    mainModel.TextCurCAD = "AutoCad 2016-简体中文(Simplified Chinese)";
                }
     
            }
            catch (Exception)
            {

                mainModel.TextCurCAD = "AutoCad 2016-简体中文(Simplified Chinese)";
            }
    


            //打开HKEY_CURRENT_USER下当前AutoCad的Applications注册表键
            RegistryKey keyApplications = Registry.CurrentUser.CreateSubKey(cadKeyName+"\\"+"Applications");
            //遍历Applications下的注册表项
            foreach (var subKeyNameApp in keyApplications.GetSubKeyNames())
            {
                //打开注册表键
                RegistryKey keyApplication = keyApplications.OpenSubKey(subKeyNameApp);
                //如果是.NET 程序
                if (keyApplication.GetValue("MANAGED") != null)
                {
                    //在列表框中添加.NET 程序的名字和程序路径
                    programModel.Name = subKeyNameApp;
                    programModel.Path = keyApplication.GetValue("LOADER").ToString();
                    this.Programs.Add(programModel);
                }
            }
        }
    }
}
